package integral

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/app/business/api/internal/svc"

	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralgoods"
	"private-domain-overseas-service/tools/ent/predicate"
)

type IntegralGoodsDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIntegralGoodsDao(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsDao {
	return &IntegralGoodsDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// IntegralGoodsConditionsFirst - 根据条件获取单个商品信息
func (l *IntegralGoodsDao) IntegralGoodsConditionsFirst(conditions ...predicate.HzIntegralGoods) (*ent.HzIntegralGoods, error) {
	goods, err := l.svcCtx.Orm.HzIntegralGoods.Query().
		Where(conditions...).
		First(l.ctx)
	if err != nil {
		return nil, err
	}
	return goods, nil
}

// IntegralGoodsConditionsPages -根据条件获取分页积分商城商品信息
func (l *IntegralGoodsDao) IntegralGoodsConditionsPages(page, pageSize int64, conditions []predicate.HzIntegralGoods) ([]*ent.HzIntegralGoods, int64, error) {
	//计算分页偏移量
	offset := common.Offset(page, pageSize)

	//查询分页数据
	goodsInfos, err := l.svcCtx.Orm.HzIntegralGoods.Query().
		Where(conditions...).
		Offset(int(offset)).
		Limit(int(pageSize)).
		Order(ent.Desc(hzintegralgoods.FieldGoodsSort)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//统计总数
	count, err := l.svcCtx.Orm.HzIntegralGoods.Query().
		Where(conditions...).Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}
	return goodsInfos, int64(count), nil
}
